package dbtesting;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */


/**
 *
 * @author zorr
 */
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.logging.Level;
import java.util.logging.Logger;

public final class PasswordService {

    private static PasswordService instance;

    private PasswordService() {
    }

    public synchronized String encrypt(String plaintext) {
        MessageDigest md = null;
        try {
            md = MessageDigest.getInstance("SHA"); //step 2
        } catch (NoSuchAlgorithmException e) {
//      throw new SystemUnavailableException(e.getMessage());
        }
        try {
            md.update(plaintext.getBytes("UTF-8")); //step 3
        } catch (UnsupportedEncodingException e) {
//      throw new SystemUnavailableException(e.getMessage());
        }

        byte raw[] = md.digest(); //step 4
        //String hash = (new BASE64Encoder()).encode(raw); //step 5
        String hexStr = "";
		for (int i = 0; i < raw.length; i++) {
			hexStr +=  Integer.toString( ( raw[i] & 0xff ) + 0x100, 16).substring( 1 );
		}
                System.out.println(hexStr);
        //return hash; //step 6
        return hexStr;
    }

    public String getHash(String password, String usernameAsSalt) {
        try {
            MessageDigest digest = null;
            try {
                digest = MessageDigest.getInstance("SHA");
            } catch (NoSuchAlgorithmException ex) {
                Logger.getLogger(PasswordService.class.getName()).log(Level.SEVERE, null, ex);
            }
            digest.reset();
            byte[] salt = usernameAsSalt.getBytes();
            digest.update(salt);
            byte raw[] = digest.digest(password.getBytes("UTF-8"));
            String hexStr = "";
            for (int i = 0; i < raw.length; i++) {
                hexStr += Integer.toString((raw[i] & 0xff) + 0x100, 16).substring(1);
            }
            System.out.println(hexStr);
            //return hash; //step 6
            return hexStr;
        } catch (UnsupportedEncodingException ex) {
            Logger.getLogger(PasswordService.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;
    }

    public static synchronized PasswordService getInstance() //step 1
    {
        if (instance == null) {
            instance = new PasswordService();
        }
        return instance;
    }
}
